package ele_handler

import (
	"fmt"
	"go-yuque/logger"
	"strings"
)

func init() {
	registerInitFunc(
		func() YuqueElementHandler {
			h := &liHandlerStruct{}
			// h.BaseHandler.self = h
			h.elements = []string{"li"}
			return h
		})
}

type liHandlerStruct struct {
	BaseHandler
}

func (li *liHandlerStruct) preHandle() error {
	if li.ctxMap != nil {
		ulOlS, ok := (li.ctxMap)[ulOlKey].([]ulOlI)
		logger.Debugf("ctx pointer:%p, ul_ol:%+v", li.ctxMap, ulOlS)
		if ok {
			curUlOlS := ulOlS[len(ulOlS)-1]

			indent := int(curUlOlS.getIndent())
			li.WriteTextContext(fmt.Sprintf("%s", strings.Repeat(" ", indent*4)))

			switch any(curUlOlS).(type) {
			case *ulStruct:
				// 当前在无序列表
				_, _ = any(curUlOlS).(*ulStruct)
				// md 语法 ul> li = -
				li.WriteTextContext("- ")
			case *olStruct:
				// 当前在有序列表
				curOlS := any(curUlOlS).(*olStruct)
				logger.Debugf("ol idx: %d", curOlS.olIdx)
				// md 语法 ol> li = 1.
				li.WriteTextContext(fmt.Sprintf("%d. ", curOlS.olIdx))
				curOlS.olIdx += 1
			}

			return nil
		}
	}
	return nil
}

func (li *liHandlerStruct) postHandle() error {
	li.WriteTextContext("\n")
	return nil
}
